package com.clickpaas.governmentcloud.service.policymatchextservice.impl;

import com.bizcloud.ipaas.tb4093760b8224c4fbcff37d3fa266753.d20210127152100.model.*;
import com.clickpaas.governmentcloud.common.ConstantExt;
import com.clickpaas.governmentcloud.common.ConstantSuggest;
import com.clickpaas.governmentcloud.common.ServerResponse;
import com.clickpaas.governmentcloud.entity.policyEntity.PolicyEntity;
import com.clickpaas.governmentcloud.service.policymatchextservice.MatchExtService;
import com.clickpaas.governmentcloud.utils.policycondcalutils.PolicyCondCal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

/**
 * @company <上海爱湃斯科技有限公司>
 * @email <zhihui.peng@clickpaas.com>
 * @author huiye
 * @decription: 上海市专精特新中小企业认定
 * @date 2020/12/16 10:31 上午
 */
@Slf4j
@Service
public class SpeciaAndNewServiceImpl implements MatchExtService {

    @Resource
    private PolicyCondCal policyCondCal;

    /**
     * 跟政策是否匹配
     * @param policy 政策对象
     * @return ServerResponse<?>
     */
    @Override
    public ServerResponse<?> isMatchSuccess(PolicyEntity policy) {
        //建议
        StringBuffer suggest = new StringBuffer();
        //返回信息
        ServerResponse<?> serverResponse = ServerResponse.createError(ConstantExt._ERROR_MESSAGE);
        //评分
        Integer score = ConstantExt._ZERO;
        //是否快速匹配：Y->true,N->false
        boolean isQuickMatch = ConstantExt.QUICK_MATCH.equals(policy.getType());
        //必要条件判断
        HashMap hashMap = necessCondi(policy);

        boolean ifNecess=Boolean.parseBoolean(hashMap.get(ConstantExt._NECESS).toString());
        if(!ifNecess){
            //专精特新只匹配公司
            return serverResponse;
        }
        //累加必要条件评分
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());
        HashMap suggAndScore = getScore(policy);
        /**
         * 累加评分
         */
        score = score + Integer.parseInt(suggAndScore.get(ConstantExt._SCORE).toString());
        /**
         * 评分为0，快速匹配不展示数据
         */
        if(score <= 0 && isQuickMatch){
            return serverResponse;
        }
        /**
         * 添加建议
         */
        suggest.append(suggAndScore.get(ConstantExt._SUGGEST).toString());
        /*if (suggest.length() == 0 && score >= 90) {
            suggest.append("建议申报");
        }*/
        /**
         * 快速匹配不添加建议
         */
        if (isQuickMatch){
            suggest = new StringBuffer();
        }
        /**
         * 必要条件不满足得0分
         */
        if(!ifNecess){
            score = 0;
        }
        return insertPolicyData(policy,score,suggest,serverResponse);
    }

    /**
     * 计算企业评分
     *
     * @param policy 匹配实体类
     * @return hashMap
     */
    @Override
    public HashMap getScore(PolicyEntity policy) {
        HashMap<String, Object> returnValue = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        StringBuffer suggest = new StringBuffer();
        /**
         * 注册资本
         */
        if (null != policy.getRegisteredCapital()
                && policy.getRegisteredCapital()>1000){
            score+=1;
        }
        /**
         * 资产总额(万元)
         */
        if (null != policy.getTotalAssets()
                && policy.getTotalAssets()>=5000){
            score+=1;
        }
        /**
         * 去年营业收入(万元)
         */
        if (null != policy.getBusinessIncomeOfLastYear()
                && policy.getBusinessIncomeOfLastYear()>=5000){
            score+=3;
        }
        if (null != policy.getBusinessIncomeOfLastYear()
                && policy.getBusinessIncomeOfLastYear()<1000){
            suggest.append(ConstantSuggest._SPE_NEW_LAST_INCOME);
        }

        /**
         * 平均营收增长率
         * （前2年主营业务收入平均增长率=[(去年主营业务收入/前年主营业务收入）^1/2－1]×100%）
         */
        if (policyCondCal.aveGrowthIncome2Year(policy)>50){
            score += 20;
        }else if (policyCondCal.aveGrowthIncome2Year(policy)>20){
            score += 15;
        }else if (policyCondCal.aveGrowthIncome2Year(policy)>10){
            score += 10;
        }else if (policyCondCal.aveGrowthIncome2Year(policy)<10){
            score += 5;
            suggest.append(ConstantSuggest._SPE_NEW_AVE_GROW_RATE);
        }

        HashMap hashMap = specialDeal(policy);
        score = score + Integer.parseInt(hashMap.get(ConstantExt._SCORE).toString());
        suggest.append(hashMap.get(ConstantExt._SUGGEST).toString());

        /**
         * 专家判断
         */
        score += 8;

        returnValue.put(ConstantExt._SCORE,score);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }

    /**
     * 写入匹配结果
     *
     * @param policy
     * @return
     */
    @Override
    public ServerResponse insertPolicyData(PolicyEntity policy,Integer score,StringBuffer suggest,ServerResponse serverResponse) {
        /**
         * 查询当前政策信息
         */
        TPoliciesDTO policyInfo = policyCondCal.getPolicyInfo(ConstantExt._RECOGNIZED_MUNICIPALITY);
        if (null == policyInfo) {
            log.info("政策：【{}】查询不到",ConstantExt._RECOGNIZED_MUNICIPALITY);
            return serverResponse;
        }
        policyCondCal.insertCommonPolicyData(policy, policyInfo, score, suggest);
        return ServerResponse.createSuccess(ConstantExt._SUCCESS_MESSAGE);
    }

    /**
     * 必要条件(精确匹配)
     * @param policy
     * @return
     */
    @Override
    public HashMap necessCondi(PolicyEntity policy){
        HashMap<String, Object> map = new HashMap<>();
        Integer score = ConstantExt._ZERO;
        map.put(ConstantExt._NECESS,true);
        StringBuffer suggStr = new StringBuffer();
        /**
         * 专精特新增加对公司名称的判断
         */
        if (StringUtils.isNotBlank(policy.getCorpName()) && !policy.getCorpName().contains("公司")){
            map.put(ConstantExt._NECESS,false);
        }
        map.put(ConstantExt._SCORE,score);
        map.put(ConstantExt._SUGGEST,suggStr);
        return map;
    }

    private HashMap specialDeal(PolicyEntity policy){
        HashMap<String, Object> returnValue = new HashMap<>();
        Integer score;
        StringBuffer suggest = new StringBuffer();

        Integer specScore = ConstantExt._ZERO;
        StringBuffer specSuggest = new StringBuffer();
        /**
         * 产品细分市场领域内排名
         */
        if ("国内前10".equals(policy.getIndustryTop10())) {
            specScore += 20;
        } else if ("国内前3或者国际前10".equals(policy.getIndustryTop10())) {
            specScore += 30;
        } else if ("国内第1或者国际前5".equals(policy.getIndustryTop10())) {
            specScore += 40;
        }else {
            specSuggest.append(ConstantSuggest._SPE_NEW_RANK);
        }
        /**
         * 市场占有率
         */
        if ("国内占有率50%以上或者国际占有率20%以上".equals(policy.getMarketShare())) {
            specScore += 10;
        } else if ("国内占有率30%-50%或者国际占有率10%-20%".equals(policy.getMarketShare())) {
            specScore += 20;
        }

        Integer preScore = ConstantExt._ZERO;
        StringBuffer preSuggest = new StringBuffer();
        /**
         * 一类二类知识产权数量
         */
        int num = policyCondCal.IntellPropertyFirst(policy) + policyCondCal.IntellPropertySecond(policy);
        if (num>=20){
            preScore += 40;
        }else if(num>=10){
            preScore += 30;
        }else if (num>1){
            preScore += 20;
        }else {
            preSuggest.append(ConstantSuggest._SPE_NEW_INTELLECTUAL);
        }
        /**
         * 研发占比（%）=前三年研发费总额/前三年营业收入总额*100%
         */
        if (policyCondCal.RDPerCostRateLastYear(policy)>=10){
            preScore += 20;
        }else if(policyCondCal.RDPerCostRateLastYear(policy)>=5){
            preScore += 15;
        }else if(policyCondCal.RDPerCostRateLastYear(policy)>=3){
            preScore += 10;
        }else {
            preSuggest.append(ConstantSuggest._SPE_NEW_RD_RATIO);
        }

        Integer excScore = ConstantExt._ZERO;
        StringBuffer excSuggest = new StringBuffer();
        /**
         * 参与标准制定（国家、地方、行业）数量
         */
        if (null != policy.getParticipateDevelopment()) {
            if (policy.getParticipateDevelopment() > 5) {
                excScore += 20;
            }else if(policy.getParticipateDevelopment() > 2){
                excScore += 15;
            }else if(policy.getParticipateDevelopment() >= 1){
                excScore += 10;
            }else {
                excSuggest.append(ConstantSuggest._SPE_NEW_STANDARD_SET);
            }
        }
        /**
         * 获得过驰名商标、著名商标、名牌产品等荣誉称号（项）
         */
        if (null != policy.getBrandCharacteristics()) {
            if (policy.getBrandCharacteristics() > 2) {
                excScore += 40;
            }else if(policy.getBrandCharacteristics() >= 2){
                excScore += 25;
            }else if(policy.getBrandCharacteristics() >= 1){
                excScore += 10;
            }else {
                excSuggest.append(ConstantSuggest._SPE_NEW_HONORARY_TITLE);
            }
        }

        Integer newScore = ConstantExt._ZERO;
        StringBuffer newSuggest = new StringBuffer();
        /**
         * 请描述产品或服务满足“四新”经济（新技术、新产业、新业态、新模式）的发展特征
         * 估值 （亿美元
         */
        BigDecimal yiyi = new BigDecimal(10000);
        BigDecimal shiyi = new BigDecimal(100000);
        if (StringUtils.isNotBlank(policy.getProductOrService())) {
            String productOrService = policy.getProductOrService();
            BigDecimal productOrService2 = policy.getProductOrService2();
            if (productOrService.contains("5G") || productOrService.contains("物联网") || productOrService.contains("人工智能") || productOrService.contains("AI") || productOrService.contains("大数据") || productOrService.contains("区块链") || productOrService.contains("生物医药")) {
                newScore += 25;
            } else if (productOrService2 != null && productOrService2.compareTo(yiyi) > -1 && productOrService2.compareTo(shiyi) < 1) {
                newScore += 40;
            } else if (productOrService2 != null && productOrService2.compareTo(shiyi) > -1) {
                newScore += 54;
            }else {
                newSuggest.append(ConstantSuggest._SPE_NEW_DEVELOP_CHARACTER);
            }
        }else {
            newSuggest.append(ConstantSuggest._SPE_NEW_DEVELOP_CHARACTER);
        }

        List<Integer> ListMaxScore = new ArrayList<>();
        ListMaxScore.add(specScore);
        ListMaxScore.add(preScore);
        ListMaxScore.add(excScore);
        ListMaxScore.add(newScore);
        //最高分
        score = Collections.max(ListMaxScore);
        if (score == specScore){
            if (StringUtils.isNotBlank(specSuggest)){
                suggest.append(specSuggest);
            }
        }
        if (score == preScore){
            if (StringUtils.isNotBlank(preSuggest)){
                suggest.append("或"+preSuggest);
            }
        }
        if (score == excScore){
            if (StringUtils.isNotBlank(excSuggest)){
                suggest.append("或"+excSuggest);
            }
        }
        if (score == newScore){
            if (StringUtils.isNotBlank(newSuggest)){
                suggest.append("或"+newSuggest);
            }
        }

        returnValue.put(ConstantExt._SCORE,score);
        returnValue.put(ConstantExt._SUGGEST,suggest);
        return returnValue;
    }
}
